package com.sg.service.biz.app.nb;

import cn.hutool.core.bean.BeanUtil;
import com.sg.common.util.CommonFunctionHelper;
import com.sg.dto.biz.app.req.*;
import com.sg.dto.biz.app.res.*;
import com.sg.dto.integration.component.QuerySemanticEngineDetailReqDto;
import com.sg.dto.integration.component.QuerySemanticEngineDetailRespDto;
import com.wicket.okrapp.common.baseinfo.BaseInfoDO;
import com.wicket.okrapp.common.baseinfo.BaseInfoHolder;
import com.wicket.okrcomponent.integration.TemplateEngineService;
import org.apache.skywalking.apm.toolkit.trace.Tag;
import org.apache.skywalking.apm.toolkit.trace.Tags;
import org.apache.skywalking.apm.toolkit.trace.Trace;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;

/**
 * @author ： 手工接入方法
 * @version 1.0
 * @since 2022/5/28 15:32
 */
@Service
public class NbBatch {


    @Resource
    private TemplateEngineService fwCompTemplateEngineClient;

    /**
     * code:receptionService
     * name:M3-传输数值0
     * desc:undefined
     * gen by moon at 8/21/2022, 5:02:14 AM
     **/
    @Trace(operationName = "M3-传输数值0")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    public ObtainReceiveFieldRespDto obtainReceiveField(ObtainReceiveFieldReqDto reqDto) {
        return BeanUtil.toBean(reqDto, ObtainReceiveFieldRespDto.class);
    }

    /**
     * code:receptionService
     * name:D3判断评价模板批次管理情况(公共)
     * desc:undefined
     * gen by moon at 8/29/2022, 12:04:28 PM
     **/
    @Trace(operationName = "D3判断评价模板批次管理情况(公共)")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    public JudgeEvaTempMgtSituationComRespDto judgeEvaTempMgtSituationCom(JudgeEvaTempMgtSituationComReqDto reqDto) {
        return BeanUtil.toBean(reqDto, JudgeEvaTempMgtSituationComRespDto.class);
    }

    /**
     * code:collectionRemoveExistingData
     * name:M3查询过滤已存在的批次设置对象（特殊方法）
     * desc:undefined
     * gen by moon at 8/29/2022, 12:09:39 PM
     **/
    @Trace(operationName = "M3查询过滤已存在的批次设置对象（特殊方法）")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    public QueryFilterBatchSetObjIdListRespDto queryFilterBatchSetObjIdList(QueryFilterBatchSetObjIdListReqDto reqDto) {
        QueryFilterBatchSetObjIdListRespDto retData = new QueryFilterBatchSetObjIdListRespDto();
        List<String> filtered = new ArrayList<>(reqDto.getEvaObjTargetCycleList());
        for (String one : reqDto.getBatchRelatedSetList()) {
            filtered.remove(one);
        }
        retData.setEvaObjTargetCycleList(filtered);
        return retData;
    }

    /**
     * code:dataAucClassification
     * name:M3检查批次等相关数据分类
     * desc:undefined
     * gen by moon at 8/29/2022, 12:14:32 PM
     **/
    @Trace(operationName = "M3检查批次等相关数据分类")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    public CheckBatchEtcDataClassRespDto checkBatchEtcDataClass(CheckBatchEtcDataClassReqDto reqDto) {
        CheckBatchEtcDataClassRespDto retData = new CheckBatchEtcDataClassRespDto();
        List<String> current = reqDto.getEvaObjTargetCycleList().stream().distinct().collect(Collectors.toList());
        List<String> inc = reqDto.getContentVirtualOrgMemberDeptList().stream().distinct().collect(Collectors.toList());
        List<String> currentCopy = new ArrayList<>(current);
        List<String> incCopy = new ArrayList<>(inc);
        current.removeAll(incCopy);
        inc.removeAll(currentCopy);
        retData.setAwaitAddBatchDeptDataClassList(inc);
        retData.setAwaitDeleteBatchDeptDataClassList(current);
        return retData;
    }

    /**
     * code:publicFieldCache
     * name:M3执行业务应用公共字段推送内存（特殊方法）
     * desc:undefined
     * gen by moon at 9/13/2022, 12:38:56 AM
     **/
    @Trace(operationName = "M3执行业务应用公共字段推送内存（特殊方法）")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    public ImplementBizPublicFieldPushMemoryRespDto implementBizPublicFieldPushMemory(ImplementBizPublicFieldPushMemoryReqDto reqDto) {
        BaseInfoDO domain = new BaseInfoDO();
        if (BaseInfoHolder.contextHolder.get() != null) {
            BeanUtil.copyProperties(BaseInfoHolder.contextHolder.get().getBaseInfo(), domain);
            BaseInfoHolder.contextHolder.remove();
        }
        if (reqDto.getSpaceId() != null) {
            domain.setSpecSpaceId(reqDto.getSpaceId());
        }

        if (reqDto.getCreateInductionId() != null) {
            domain.setSpecInductionRecordId(reqDto.getCreateInductionId());
        }

        if (reqDto.getAppId() != null) {
            domain.setSpecAppId(reqDto.getAppId());
        }

        if (reqDto.getHighestOrgID() != null) {
            domain.setSpecHighestOrgID(reqDto.getSpecHighestOrgID());
        }

        if (reqDto.getUserId() != null) {
            domain.setSpecUserId(reqDto.getUserId());
        }

        if (reqDto.getOriginalRoleMemberId() != null) {
            domain.setSpecOriginalRoleMemberId(reqDto.getOriginalRoleMemberId());
        }

        CommonFunctionHelper.setBaseInfoToLocal(domain);
        return new ImplementBizPublicFieldPushMemoryRespDto();
    }

    /**
     * code:generateSemanticInstance
     * name:M3-生成语义内容
     * desc:undefined
     * gen by moon at 9/13/2022, 12:39:35 AM
     **/
    @Trace(operationName = "M3-生成语义内容")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    public GenerateSemanticContentRespDto generateSemanticContent(GenerateSemanticContentReqDto reqDto) {
        boolean bRetFlag = false;
        GenerateSemanticContentRespDto retData = new GenerateSemanticContentRespDto();
        String retConent = "";
        QuerySemanticEngineDetailReqDto querySemanticEngineDetailReqDto = new QuerySemanticEngineDetailReqDto();
        querySemanticEngineDetailReqDto.setTemplateSemanticEngineCode("CREATE_TEMP_BATCH_NAME");
        QuerySemanticEngineDetailRespDto querySemanticEngineDetailRespDto = fwCompTemplateEngineClient.querySemanticEngineDetail(querySemanticEngineDetailReqDto).getData();
        if (querySemanticEngineDetailRespDto != null && querySemanticEngineDetailRespDto.getTemplateEngineTemplate() != null) {
            String targetContName = "\\{targetContName}";
            String systemDateTime = "\\{systemDateTime}";
            String sixRandomNum = "\\{sixRandomNum}";
            if (reqDto.getTargetContentName() != null && !reqDto.getTargetContentName().isEmpty()) {
                bRetFlag = true;
                retConent = querySemanticEngineDetailRespDto.getTemplateEngineTemplate().replaceAll(targetContName, reqDto.getTargetContentName());
                retConent = retConent.replaceAll(systemDateTime, CommonFunctionHelper.date2Str(CommonFunctionHelper.getCurrentTime()));
                retConent = retConent.replaceAll(sixRandomNum, String.valueOf((Math.random() * 9 + 1) * 100000));
            } else {
                retConent = querySemanticEngineDetailRespDto.getTemplateEngineTemplate().replaceAll(targetContName, "---");
            }

            if (retConent != null && !retConent.isEmpty()) {
                retConent = retConent.replaceAll("---", "");
                retConent = retConent.replaceAll("（）", "");
                retData.setObjectName(retConent);
            }

            if (bRetFlag) {
                return retData;
            }

        }
        return retData;
    }

    /**
     * code:collectionRemoveExistingData
     * name:M3查询过滤一级部门列表(特殊方法)
     * desc:undefined
     * gen by moon at 9/13/2022, 5:53:54 PM
     **/
    @Trace(operationName = "M3查询过滤一级部门列表(特殊方法)")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    public QueryFilterFristDeptListRespDto queryFilterFristDeptList(QueryFilterFristDeptListReqDto reqDto) {
        QueryFilterFristDeptListRespDto retData = new QueryFilterFristDeptListRespDto();
        List<String> filterdList = new ArrayList<>(reqDto.getVirtualOrgMemberDeptList());
        for (String one : reqDto.getEvaObjTargetCycleList()) {
            filterdList.remove(one);
        }
        retData.setVirtualOrgMemberDeptList(filterdList);
        return retData;
    }

    /**
     * code:receptionService
     * name:M3评价模板首次管理场景
     * desc:undefined
     * gen by moon at 9/14/2022, 11:31:40 PM
     **/
    @Trace(operationName = "M3评价模板首次管理场景")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    public ImplementBizConstructAccessParameterFieldRespDto implementBizConstructAccessParameterField(ImplementBizConstructAccessParameterFieldReqDto reqDto) {
        return BeanUtil.toBean(reqDto, ImplementBizConstructAccessParameterFieldRespDto.class);
    }

    /**
     * code:generateSemanticInstance
     * name:M3-生成语义内容
     * desc:undefined
     * gen by moon at 10/24/2022, 9:15:44 PM
     **/
    @Trace(operationName = "M3-生成语义内容")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    public GenerateEvaTempBatchNameRespDto generateEvaTempBatchName(GenerateEvaTempBatchNameReqDto reqDto) {

        // {systemDateTime}{randomNumberDigits}{targetContentName}批次
        boolean bRetFlag = false;
        GenerateEvaTempBatchNameRespDto retData = new GenerateEvaTempBatchNameRespDto();
        String retConent = "";

        QuerySemanticEngineDetailReqDto querySemanticEngineDetailReqDto = new QuerySemanticEngineDetailReqDto();
        querySemanticEngineDetailReqDto.setTemplateSemanticEngineCode("GENERATE_EVA_TEMP_BATCH_NAME");
        QuerySemanticEngineDetailRespDto querySemanticEngineDetailRespDto = fwCompTemplateEngineClient.querySemanticEngineDetail(querySemanticEngineDetailReqDto).getData();
        if (querySemanticEngineDetailRespDto != null && querySemanticEngineDetailRespDto.getTemplateEngineTemplate() != null) {
            String systemDateTime = "\\{systemDateTime}";
            String randomNumberDigits = "\\{randomNumberDigits}";
            String targetContentName = "\\{targetContentName}";
            if (reqDto.getTargetContentName() != null && !reqDto.getTargetContentName().isEmpty()) {
                bRetFlag = true;
                retConent = querySemanticEngineDetailRespDto.getTemplateEngineTemplate().replaceAll(targetContentName, reqDto.getTargetContentName());
                retConent = retConent.replaceAll(systemDateTime, CommonFunctionHelper.date2Str(CommonFunctionHelper.getCurrentTime()));
                Random random = new Random();
                String result = "";
                for (int i = 0; i < reqDto.getRandomNumberDigits(); i++) {
                    result += random.nextInt(10);
                }
                retConent = retConent.replaceAll(randomNumberDigits, result);
            } else {
                retConent = querySemanticEngineDetailRespDto.getTemplateEngineTemplate().replaceAll(targetContentName, "---");
            }

            if (retConent != null && !retConent.isEmpty()) {
                retConent = retConent.replaceAll("---", "");
                retConent = retConent.replaceAll("（）", "");
                retData.setObjectName(retConent);
            }

            if (bRetFlag) {
                return retData;
            }

        }
        return retData;
    }

    /**
     * code:receptionService
     * name:M3获取接收外部字段(特殊方法）
     * desc:undefined
     * gen by moon at 10/27/2022, 3:14:49 PM
     **/
    @Trace(operationName = "M3获取接收外部字段(特殊方法）")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    public ObtainReceiveOutFieldRespDto obtainReceiveOutField(ObtainReceiveOutFieldReqDto reqDto) {
        return BeanUtil.toBean(reqDto, ObtainReceiveOutFieldRespDto.class);
    }

    /**
     * code:receptionService
     * name:M3接收上文批次信息（批次ID+批次标识）
     * desc:undefined
     * gen by moon at 2/1/2023, 4:53:33 PM
     **/
    @Trace(operationName = "M3接收上文批次信息（批次ID+批次标识）")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    public ImplementAccessParameterBizFieldRespDto implementAccessParameterBizField(ImplementAccessParameterBizFieldReqDto reqDto) {
        return BeanUtil.toBean(reqDto, ImplementAccessParameterBizFieldRespDto.class);
    }

    /**
     * code:receptionService
     * name:M3约定是否统一管理为【是】
     * desc:undefined
     * gen by moon at 4/20/2023, 1:33:13 AM
     **/
    @Trace(operationName = "M3约定是否统一管理为【是】")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    public ImplementAcceptFieldRespDto implementAcceptField(ImplementAcceptFieldReqDto reqDto) {
        return BeanUtil.toBean(reqDto, ImplementAcceptFieldRespDto.class);
    }

    /**
     * code:receptionService
     * name:M3约定评价模板管理员
     * desc:undefined
     * gen by moon at 10/9/2023, 8:57:18 PM
     **/
    @Trace(operationName = "M3约定评价模板管理员")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    public ImplementGainInParameterFieldsRespDto implementGainInParameterFields(ImplementGainInParameterFieldsReqDto reqDto) {
        return BeanUtil.toBean(reqDto, ImplementGainInParameterFieldsRespDto.class);
    }
    //手工接入方法
}
